# -*- coding: utf-8 -*-

import gtk
import os.path
from Simulinux import config

#@todo: read all the necessary library information from XML file
#(pixbuf, name, text to be showed on the combobox, id, description, etc)

LIBS = ['math', 'sources', 'sinks']

class Palette:
    
    def __init__(self, builder):
        self.__builder = builder      
        self.__combo = self.__builder.get_object("combobox_libraries")
        self.__parts = self.__builder.get_object("treeview_parts")
        self.__textbuffer = self.__builder.get_object("textbuf_part_description")
        self.__models = {}
        for i in LIBS:
            self.__models[i] = self.__builder.get_object("liststore_parts_%s" % i)
        self.__config_combobox()
        self.__config_treeview()

    def drag_data_get(self, widget, context, selection, targetType, eventTime):
        treeselection = self.__parts.get_selection()
        model, iter = treeselection.get_selected()
        block = model.get_value(iter, 0)
        selection.set(selection.target, 8, block)
        
    def library_changed(self, widget, *data):
        number = self.__combo.get_active()
        self.__select_library(number)
        self.__textbuffer.set_text('')
        
    def block_selected(self, widget, *data):
        treeselection = self.__parts.get_selection()
        model, iter = treeselection.get_selected()
        self.__textbuffer.set_text(model.get_value(iter, 3)) #description

    def __config_combobox(self):
        cell = self.__builder.get_object('combobox_icon')
        cell.set_property('xalign', 0)
        cell.set_property('xpad', 5)
        cell.set_property('width', 80)
        number = 2 #sources
        self.__combo.set_active(number)
        self.__select_library(number)
        
    def __select_library(self, number):
        #Associating combo with the model and selecting first library
        iter = self.__combo.get_model().get_iter(number)
        refname = self.__combo.get_model().get_value(iter, 0)
        self.__parts.set_model(self.__models[refname])
        
    def __config_treeview(self):
        self.__parts.enable_model_drag_source(
            gtk.gdk.BUTTON1_MASK, 
            [('x-application/simulinux-part', gtk.TARGET_SAME_APP, 1)], 
            gtk.gdk.ACTION_COPY
        )
